//
//  ViewController.m
//  PullRefresh
//
//  Created by Sunny Purewal on 11-10-30.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "TableViewController.h"

#define HEADER_HEIGHT 60.0f

@implementation TableViewController

@synthesize refreshText,releaseText,refreshingText,delegate;

#pragma mark properties
-(void)setFont:(UIFont *)font
{
    [lblRefresh setFont:font];
}

-(void)setImage:(UIImage *)image
{
    CGSize size = self.view.frame.size;
    [imgArrow setImage:image];
    [imgArrow setFrame:CGRectMake(size.width/20, (HEADER_HEIGHT-image.size.height)/2, image.size.width, image.size.height)];
}

#pragma mark implementation
-(void)addPullToRefreshHeader
{
    CGSize size = self.view.frame.size;
    UIView* header = [[UIView alloc] initWithFrame:CGRectMake(0, 0 - HEADER_HEIGHT, size.width, size.height)];
    [header setBackgroundColor:[UIColor clearColor]];
    
    lblRefresh = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, HEADER_HEIGHT)];
    [lblRefresh setBackgroundColor:[UIColor clearColor]];
    [lblRefresh setTextAlignment:UITextAlignmentCenter];
    [lblRefresh setNumberOfLines:2];
    [lblRefresh setFont:[UIFont boldSystemFontOfSize:12.0]];
    
    UIImage* image = [UIImage imageNamed:@"arrow.png"];
    imgArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"]];
    [imgArrow setFrame:CGRectMake(size.width/20, (HEADER_HEIGHT-image.size.height)/2, image.size.width, image.size.height)];
    
    spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [spinner setFrame:CGRectMake(size.width/20, (HEADER_HEIGHT-48)/2, 48, 48)];
    [spinner setHidesWhenStopped:YES];
    
    [header addSubview:lblRefresh];
    [header addSubview:imgArrow];
    [header addSubview:spinner];
    [self.tableView addSubview:header];
}

-(void)refresh
{
    [delegate refresh];
    [self performSelector:@selector(doneRefreshing) withObject:nil afterDelay:2.0];
}

-(void)doneRefreshing
{
    [UIView animateWithDuration:0.25 animations:^{
        [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        [spinner stopAnimating];
    } completion:^(BOOL finished) {
        [lblRefresh setText:refreshText];
        [imgArrow setTransform:CGAffineTransformMakeRotation(0)];
        [imgArrow setHidden:NO];
    }];
}

#pragma mark scroll view delegate

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [lblRefresh setText:refreshText];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yOffset = scrollView.contentOffset.y;
    CGFloat topInset = scrollView.contentInset.top;
    
    if (topInset > 0) {
    }
    else if (yOffset < 0) {
        if (yOffset < -HEADER_HEIGHT) {
            [UIView animateWithDuration:0.25 animations:^{
                [lblRefresh setText:releaseText];
                [imgArrow setTransform:CGAffineTransformMakeRotation(M_PI)];
            }];            
        }
        else {
            [UIView animateWithDuration:0.25 animations:^{
                [lblRefresh setText:refreshText];
                [imgArrow setTransform:CGAffineTransformMakeRotation(M_PI*2)];
            }];
        }
    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView.contentOffset.y < -HEADER_HEIGHT) {
        [UIView animateWithDuration:0.25 animations:^{
            [lblRefresh setText:refreshingText];
            [imgArrow setHidden:YES];
            [self.tableView setContentInset:UIEdgeInsetsMake(HEADER_HEIGHT, 0, 0, 0)];
            [spinner startAnimating];
        }];
        
        [self refresh];
    }
}

#pragma mark init
-(id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        refreshText = NSLocalizedStringWithDefaultValue(@"lblPullToRefresh",
                                          nil,
                                          [NSBundle mainBundle],
                                          @"Pull to Refresh",
                                          @"pull to refresh label");
        
        releaseText = NSLocalizedStringWithDefaultValue(@"lblReleaseToRefresh",
                                          nil,
                                          [NSBundle mainBundle],
                                          @"Release to Refresh",
                                          @"release to refresh label");
        
        refreshingText = NSLocalizedStringWithDefaultValue(@"lblRefreshing",
                                                           nil,
                                                           [NSBundle mainBundle],
                                                           @"Refreshing",
                                                            @"pulled to refresh, now refreshing");
    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    //add the header view
    [self addPullToRefreshHeader];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end
